#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 在第0行插入行
    ui->tableWidget->insertRow(0);
    ui->tableWidget->insertRow(0);
    ui->tableWidget->insertRow(0);

    // 在第0列插入列
    ui->tableWidget->insertColumn(0);
    ui->tableWidget->insertColumn(0);
    ui->tableWidget->insertColumn(0);

    // 为每列设置列名（列名：水平方向的表头）
    ui->tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("学号"));
    ui->tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("姓名"));
    ui->tableWidget->setHorizontalHeaderItem(2,new QTableWidgetItem("年龄"));

    // 为表中添加数据
    ui->tableWidget->setItem(0,0,new QTableWidgetItem("1001"));
    ui->tableWidget->setItem(0,1,new QTableWidgetItem("石昊"));
    ui->tableWidget->setItem(0,2,new QTableWidgetItem("22"));

    ui->tableWidget->setItem(1,0,new QTableWidgetItem("1002"));
    ui->tableWidget->setItem(1,1,new QTableWidgetItem("叶凡"));
    ui->tableWidget->setItem(1,2,new QTableWidgetItem("20"));

    ui->tableWidget->setItem(2,0,new QTableWidgetItem("1003"));
    ui->tableWidget->setItem(2,1,new QTableWidgetItem("王林"));
    ui->tableWidget->setItem(2,2,new QTableWidgetItem("21"));
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_insertRow_clicked()
{
    // 获取行数
    int currentRow = ui->tableWidget->rowCount();
    // 添加行
    ui->tableWidget->insertRow(currentRow);
}

void Widget::on_pushButton_deleteRow_clicked()
{
    // 获取当前选中行数
    int currentRow = ui->tableWidget->currentRow();
    // 删除当前选中行
    ui->tableWidget->removeRow(currentRow);
}

void Widget::on_pushButton_insertColumn_clicked()
{
    // 获取列数
    int currentColumn = ui->tableWidget->columnCount();
    // 添加列
    ui->tableWidget->insertColumn(currentColumn);
    // 添加纵向表头
    const QString& name = ui->lineEdit->text();
    ui->tableWidget->setHorizontalHeaderItem(currentColumn,new QTableWidgetItem(name));
}

void Widget::on_pushButton_deleteColumn_clicked()
{
    // 获取当前所选列数
    int currentColumn = ui->tableWidget->currentColumn();
    // 删除列
    ui->tableWidget->removeColumn(currentColumn);
}
